package com.hqd.jjvm.rtda.memory;

import com.hqd.jjvm.rtda.heap.classloader.JClassLoader;
import com.hqd.jjvm.rtda.obj.JString;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 字符串常量池
 */
public class JStringPool {
    private static final Map<String, JString> STRING_POOL = new ConcurrentHashMap<>();
    private static final JStringPool instance = new JStringPool();

    public void addString(JClassLoader loader, String val) {
        STRING_POOL.put(val, JString.newJString(loader, val));
    }

    public static JStringPool getInstance() {
        return instance;
    }

    public JString getStringVal(String key) {
        return STRING_POOL.get(key);
    }

    public JString internString(JClassLoader loader, String key) {
        if (getStringVal(key) == null) {
            addString(loader, key);
        }
        return getStringVal(key);
    }

    public Map<String, JString> getStringPool() {
        return STRING_POOL;
    }
}
